package GUI;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.Timer;

import Game.Player;
import Game.Tile;

public class GamePanel extends JLabel implements KeyListener, ActionListener {

	Player player;
	int[][]map;
	private BufferedImage img;
	/*
	 * Movement velocity
	 */
	int velocityX;
	int velocityY;
	
	int x;
	int y;
	
	Timer t = new Timer(50, this);

	public GamePanel() {
		
		map = Tile.initializeMap();
		player = new Player("Aleks");
		x = player.getX();
		y = player.getY();
		
	    try {
	        img = ImageIO.read(new File("grass.png"));
	      } catch(IOException e) {
	        e.printStackTrace();
	      }
		
		t.start();
		addKeyListener(this);
		setFocusable(true);
		setFocusTraversalKeysEnabled(false);
	}
	 
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
		g.drawImage(player.icon, x, y, this);
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if(!checkCollision())
		{
			x += velocityX;
			y += velocityY;
			repaint();
		}
	}
	public void up()
	{
		velocityX = 0;
		velocityY = -player.getBaseVel();
	}
	public void down()
	{
		velocityX = 0;
		velocityY = player.getBaseVel();
	}
	public void left()
	{
		velocityX = -player.getBaseVel();
		velocityY = 0;
	}
	public void right()
	{
		velocityX = player.getBaseVel();
		velocityY = 0;
	}
	
	public void keyPressed(KeyEvent e)
	{
		int code = e.getKeyCode();
		if(code == KeyEvent.VK_UP)
		{
			up();
		}
		if(code == KeyEvent.VK_DOWN)
		{
			down();
		}
		if(code == KeyEvent.VK_LEFT)
		{
			left();
		}
		if(code == KeyEvent.VK_RIGHT)
		{
			right();
		}
		if(code == KeyEvent.VK_ESCAPE)
		{
			System.exit(0);
		}
	}
	
	public void keyTyped(KeyEvent e) {		
	}
	
	public void keyReleased(KeyEvent e) {		
		velocityX = 0;
		velocityY = 0;
		System.out.println(x/20+" "+y/20);		
	}
	
	public boolean checkCollision()
	{
		/*
		 * Check collision
		 */
		try{
		if(map[(x+velocityX)/20][(y+velocityY)/20]==1)
		{
			return true;
		}
		}
		catch(java.lang.ArrayIndexOutOfBoundsException e)
		{
			return true;
		}
		return false;
	}
}